package com.jule.robot.service.thread;

import com.jule.core.jedis.JedisPoolWrap;
import com.jule.core.jedis.StoredObjManager;
import com.jule.db.entities.RoomConfigModel;
import com.jule.robot.config.Config;
import com.jule.robot.service.holder.RobotClientHolder;
import com.jule.robot.service.holder.RobotUserHolder;
import com.jule.robot.service.holder.RoomConfigHolder;
import com.jule.robot.util.RunTime;
import com.jule.robot.util.StringTools;
import com.jule.robot.valve.gate.RobotJoinTableThreadPoolManager;
import com.jule.teenpatti.base.enums.RedisConst;
import com.jule.teenpatti.base.model.RoomTableRelationModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class CheckNullTableIsNeedRobot implements Runnable {
    private final static Logger logger = LoggerFactory.getLogger(CheckNullTableIsNeedRobot.class);
    private int gameId;

    public CheckNullTableIsNeedRobot(int gameId){
        this.gameId = gameId;
    }

    public void run() {
        try {
            RunTime runTime = new RunTime("CheckNullTableIsNeedRobot");
            if(Config.ROBOT_JOIN_NULL_TABLE == 1){
                logger.info(">>>>>>>>>>>>>>>>>>>检查是否有空桌需要加入机器人-开始。 gameId->{}", gameId);
                int totalOnLinePlayer = 0;
                for (RoomConfigModel roomConfigModel : RoomConfigHolder.getInstance().getAllRoomConfig()) {
                    String roomId = roomConfigModel.getRoomId();
                    String key4RoomTableRelation = new StringBuilder().append(RedisConst.TABLE_INSTANCE.getProfix()).append(gameId).append(roomId).toString();
                    Map<String, String> tableMap = JedisPoolWrap.getInstance().hGetAll(key4RoomTableRelation);
                    for (String key : tableMap.keySet()) {
                        RoomTableRelationModel model = StoredObjManager.getStoredObjInMap(RoomTableRelationModel.class, key4RoomTableRelation, key);
                        if (null != model) {
                            String tableId = model.getTableId();
                            String cacheKeyPrefix = new StringBuilder().append(gameId).append("|").append(roomId).append("|").append(tableId).append("|").toString(); //缓存前缀（验证机器人入场时间间隔的缓存）
                            String key4tableSeat = new StringBuilder().append(RedisConst.TABLE_SEAT.getProfix()).append(gameId).append(roomId).append(tableId).toString();
                            Map<String, String> seatMap = JedisPoolWrap.getInstance().hGetAll(key4tableSeat);

                            //是否清除了脏数据（Redis中残留的已断开连接的机器人账号数据）
                            boolean isClearedDirtyDate = RobotClientHolder.clearUnActiveRobotOnTable(seatMap, gameId+"", roomId, tableId,roomConfigModel.getAnte(), key4tableSeat);
                            if(isClearedDirtyDate) {
                                seatMap = JedisPoolWrap.getInstance().hGetAll(key4tableSeat);
                                logger.error("桌子状态检查-Redis数据清除后（检查空桌）：gameId->{}, roomId->{}, tableId->{}, seatMap.size->{}, ante->{}, key4tableSeat->{}",
                                        gameId, roomId, tableId, seatMap.size(), roomConfigModel.getAnte(), key4tableSeat);
                            }
                            totalOnLinePlayer += seatMap.size();

                            //检查桌子ID，如果桌子ID大于4，那么不向此空桌增加机器人。
                            if(StringTools.getNumberByEndOfString(tableId, 2) > 4){
                                //如果桌子ID大于4，说明空桌已经伸缩创建的太多，因此不向此空桌中加入机器人，以免出现机器人无谓的加入太多空桌，并造成game服务创建更多的空桌
                                continue;
                            }

                            //如果需要增加机器人到空桌中
                            if(seatMap.size() == 0 && Config.ROBOT_JOIN_NULL_TABLE == 1 && roomConfigModel.getAnte() <= Config.ROBOT_JOIN_NULL_MAX_ANTE){
                                int joinNullTableMaxRobotNum = Config.ROBOT_DESK_ROBOT_NUM;
                                logger.warn("向 空桌 补位机器人 {} 个，gameId->{}, roomId->{}, tableId->{}, ante->{}", joinNullTableMaxRobotNum, gameId, roomId, tableId, roomConfigModel.getAnte());
                                for(int i=0; i<joinNullTableMaxRobotNum; i++){
                                    RobotUserHolder.setNullTableToJoinRobot(gameId+"", roomId, tableId);
                                    RobotJoinTableThreadPoolManager.getInstance().addTask(new JoinRobotToTableThread(gameId, roomId, tableId, "加入空桌"));
                                }
                            }
                            Thread.sleep(500); //暂停500毫秒，给之前入桌的机器人留出处理时间。避免同时并发入桌，造成Game服务器崩溃
                        }
                    }
                }
                logger.info("<<<<<<<<<<<<<<<<<<<检查是否有空桌需要加入机器人-结束。 gameId->{}", gameId);
                runTime.getSecsBuyAlreadyRun(2);
            }
        } catch (Exception ex) {
            logger.error("CheckNullTableIsNeedRobot ERROR, msg = " + ex.getMessage(), ex);
        }
        finally {

        }
    }

}
